import jsonpath

from text_litemall_leimu.api.base_api import BaseApi
from utils.log_util import logger


class ProductApi(BaseApi):
    # 商品类目增加
    def add(self):
        print(self.token)
        logger.info("存放数据")
        info = {
            "method": "POST",
            "url": f"{self.base_url}admin/category/create",
            "headers": {'X-Litemall-Admin-Token': self.token},
            "json": {"name":self.name,"level":"L2","pid":0}
        }
        logger.info("调用接口")
        r = self.request(**info)
        logger.info(f"响应内容为{r.json()}")
        return r
    def search(self):
        logger.info("存放数据")
        info = {
            "method": "GET",
            "url": f"{self.base_url}admin/category/list",
            "headers": {'X-Litemall-Admin-Token': self.token},
        }
        logger.info("调用接口")
        r = self.request(**info)
        logger.info(f"name为{self.name}")
        self.id = jsonpath.jsonpath(r.json(), expr=f"$..[?(@.name == {self.name})].id")
        logger.info(f"响应内容为{r.json()}")
        logger.info(f"id为{self.id}")
        return r
    # 商品类目修改
    def update(self):
        logger.info("存放数据")
        info = {
            "method": "POST",
            "url": f"{self.base_url}admin/category/update",
            "headers": {'X-Litemall-Admin-Token': self.token},
            "json": {
                "name":self.new_name,
                "level": "L2",
                "pid": 0
            }
        }
        logger.info("调用接口")
        r = self.request(**info)
        logger.info(f"响应内容为{r.json()}")
        return r

    def delete(self):
        logger.info("存放数据")
        info = {
            "method":"POST",
            "url":f"{self.base_url}admin/category/delete",
            "headers" : {'X-Litemall-Admin-Token': self.token},
            "json":{
                "id":self.id
            }
        }
        logger.info("调用接口")
        r = self.request(**info)
        logger.info(f"响应内容为{r.json()}")
        return  r
